package com.sprint.lb.impl;

import com.sprint.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalanceImpl implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);//元子类

    //自旋锁的步骤
    public final int getAndIncrement(){
        int current;
        int  next;
        do {
           current=this.atomicInteger.get();

           next = current >= 2147483647 ? 0:current+1;
        }while(!atomicInteger.compareAndSet(current,next));
        //判断期望值和实际值是否一致，不一直继续
        System.out.println(" 第几次运行******* " + next);
         return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        System.out.println(" 当前值******* " + this.atomicInteger.get());
        int i = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(i);
    }
}
